<template>
  <div class="container">
    <h2 class="page-title">订单列表</h2>
    <el-table
        :data="paginatedOrders"
        style="width: 100%"
        border
    >
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template #default="props">
          <div class="detail-card">
            <div class="section">
              <h4>买家备注</h4>
              <p>{{ props.row.remark || '无' }}</p>
            </div>
            <div class="section">
              <h4>商品信息</h4>
              <ul>

                <li>名称：{{ props.row.productName }}</li>
                <li>数量：{{ props.row.quantity }}</li>
                <li>单价：{{ props.row.productPrice }}</li>
              </ul>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="订单号" width="100" />
      <el-table-column prop="buyerName" label="买家" />
      <el-table-column prop="productName" label="商品名称" />
      <el-table-column prop="totalPrice" label="总价" />
      <el-table-column prop="createdAt" label="订单日期" />
<!--      <el-table-column label="标签" width="120">-->
<!--        <template #default="scope">-->
<!--          <div class="order-tags">-->
<!--&lt;!&ndash;            <span v-if="scope.row.confirmation === '未确认'">🕒 待确认</span>&ndash;&gt;-->
<!--            <span v-if="scope.row.confirmation === 0">🕒 待确认</span>-->
<!--            <span v-if="scope.row.totalPrice > 1000">💰 高价值</span>-->
<!--            <span v-if="scope.row.remark && /急|尽快/.test(scope.row.remark)">⚠️ 急单</span>-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="标签" width="160">
        <template #default="scope">
          <!-- 使用 Element Plus Tag，颜色统一，支持动态循环 -->
          <el-tag
              v-for="tag in getTags(scope.row)"
              :key="tag.label"
              :type="tag.type"
              :class="`tag-${tag.type}`"
              effect="plain"
              round
              style="margin: 2px 4px;"
          >
            {{ tag.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
<!--          <span v-if="scope.row.confirmation === '未确认'">待确认</span>-->
          <span v-if="scope.row.confirmation === 0">待确认</span>
          <span v-else>{{ scope.row.displayStatus || '未知状态' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" :min-width="150">
        <template #default="scope">
          <div class="action-btns">
            <!-- ① 待确认：确认 + 取消 + 详情 -->
            <template v-if="scope.row.confirmation === 0">
              <el-button size="small" type="warning"
                         @click="confirmOrder(scope.row.id)">确认</el-button>
              <el-button size="small" type="danger"
                         @click="cancelOrder(scope.row.id)">取消</el-button>
              <el-button size="small" type="primary"
                         @click="viewOrderDetails(scope.row.id)">详情</el-button>
            </template>

            <!-- ② 已确认但未备货：备货 + 详情 -->
            <template v-else-if="scope.row.stockUp === 0">
              <el-button size="small" type="success"
                         @click="stockUp(scope.row.id)">备货完成</el-button>
              <el-button size="small" type="primary"
                         @click="viewOrderDetails(scope.row.id)">详情</el-button>
            </template>

            <!-- ③ 已备货但未发货：发货 + 详情 -->
            <template v-else-if="scope.row.sendOrder === 0">
              <el-button size="small" type="success"
                         @click="sendOrder(scope.row.id)">发货</el-button>
              <el-button size="small" type="primary"
                         @click="viewOrderDetails(scope.row.id)">详情</el-button>
            </template>

            <!-- ④ 已发货或已完成：仅详情 -->
            <template v-else>
              <el-button size="small" type="primary"
                         @click="viewOrderDetails(scope.row.id)">详情</el-button>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>


    <!-- 没有数据时的提示 -->
<!--    <p v-else>暂无订单数据</p>-->

    <!-- 分页 -->
    <div class="pagination">
      <button
          class="button page-btn"
          :disabled="pageNum <= 1"
          @click="changePage(pageNum - 1)"
      >
        上一页
      </button>
      <span>第 {{ pageNum }} 页</span>
      <button
          class="button page-btn"
          :disabled="pageNum >= totalPages"
          @click="changePage(pageNum + 1)"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request.js";
export default {
  data() {
    return {
      orders: [],   // 后端返回的订单列表
      pageNum: 1,
      pageSize: 10,
      total: 0,
      totalPages: 0

    };
  },
  methods: {
    // 跳转到订单详情页
    viewOrderDetails(orderId) {
      this.$router.push({ name: 'OrderDetails', params: { id: orderId } });
    },
    async fetchOrders() {
      try {
        const res = await request.get('/order/selectOrders', {
          params: { pageNum: this.pageNum, pageSize: this.pageSize }
        })

        if (res.code !== '200') {
          ElMessage.error(res.msg || '获取订单失败')
          return
        }

        this.orders = res.data.map(o => ({
          id:           o.id,
          buyerId:      o.buyerId,
          buyerName:    o.buyerName,
          productName:  o.productName,
          totalPrice:   o.totalPrice,
          createdAt:    o.createdAt,
          quantity:     o.quantity,
          productPrice: o.price,
          confirmation: o.confirmation,
          stockUp:      o.stockUp     ?? 0,
          sendOrder:    o.sendOrder   ?? 0,
          completion:   o.completion  ?? 0,
          remark:       o.remark      || '',
          displayStatus: (o.display_status ?? o.displayStatus)
              ?? this.getOrderStatusText(o.orderStatus)
        }))

        this.total      = this.orders.length
        this.totalPages = Math.ceil(this.total / this.pageSize)
      } catch (err) {
        console.error('获取订单失败:', err)
        ElMessage.error('获取订单失败')
      }
    },
    getOrderStatusText(status) {
      switch (status) {
        case 'PAID':
          return '待发货';
        case 'SHIPPED':
          return '已发货';
        case 'COMPLETED':
          return '已完成';
        case 'UNPAID':
          return '未支付';
        default:
          // status 可能已是中文或 null/undefined
          return status || '未知状态';
      }
    },
    async confirmOrder(orderId) {
      try {
        const res = await request.put(`/order/confirmation/${orderId}`)
        if (res.code === '200') {
          ElMessage.success('订单已确认，待备货')
          this.fetchOrders()
        } else {
          ElMessage.error(res.msg || '确认订单失败')
        }
      } catch (err) {
        console.error('确认订单异常:', err)
        ElMessage.error('确认订单失败')
      }
    },
    async stockUp(orderId) {
      try {
        const res = await request.put(`/order/stockup/${orderId}`)
        if (res.code === '200') {
          ElMessage.success('备货完成，待发货')
          this.fetchOrders()
        } else {
          ElMessage.error(res.msg || '备货失败')
        }
      } catch (err) {
        console.error('备货异常:', err)
        ElMessage.error('备货异常')
      }
    },
    // 发货
    // sendOrder(orderId) {
    //   fetch(`http://localhost:8080/order/sendorder/${orderId}`, {
    //     method: 'PUT'
    //   })
    //       .then(r => r.json())
    //       .then(res => {
    //         if (res.code === '200') {
    //           this.$message.success('已发货，等待买家收货');
    //           this.fetchOrders();
    //         } else {
    //           this.$message.error(res.msg || '发货失败');
    //         }
    //       })
    //       .catch(err => {
    //         console.error('发货异常:', err);
    //         this.$message.error('发货异常');
    //       });
    // },
    async sendOrder(orderId) {
      try {
        const res = await request.put(`/order/sendorder/${orderId}`)
        if (res.code === '200') {
          ElMessage.success('已发货，等待买家收货')
          this.fetchOrders()
        } else {
          ElMessage.error(res.msg || '发货失败')
        }
      } catch (err) {
        console.error('发货异常:', err)
        ElMessage.error('发货异常')
      }
    },
    async cancelOrder(orderId) {
      try {
        const res = await request.delete(`/order/sellerCancel/${orderId}`)
        if (res.code === '200') {
          ElMessage.success('订单已取消')
          this.fetchOrders()
        } else {
          ElMessage.error(res.msg || '取消订单失败')
        }
      } catch (err) {
        console.error('取消订单异常:', err)
        ElMessage.error('取消订单异常')
      }
    },
    // 分页
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.pageNum = page;
        this.fetchOrders();
      }
    },
    getTags(row) {
      const tags = [];
      if (row.confirmation === 0) {
        tags.push({ label: '待确认', type: 'warning' });
      }
      if (row.totalPrice > 1000) {
        tags.push({ label: '高价值', type: 'success' });
      }
      if (row.remark && /急|尽快/.test(row.remark)) {
        tags.push({ label: '急单', type: 'danger' });
      }
      // 如果没有以上任何标签，给一个“普通”
      if (tags.length === 0) {
        tags.push({ label: '普通', type: 'info' });
      }
      return tags;
    },
  },
  computed: {
    paginatedOrders() {
      const start = (this.pageNum - 1) * this.pageSize;
      const end = this.pageNum * this.pageSize;
      return this.orders.slice(start, end);
    },
  },
  watch: {
    pageNum() {
      this.fetchOrders();
    },
  },
  mounted() {
    this.fetchOrders();
  },
};
</script>

<style scoped>
.container {
  max-width: 1100px;
  margin: 30px auto;
  padding: 24px 30px;
  background-color: #fdfdfd;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  font-family: "Segoe UI", sans-serif;
}
.el-table {
  border-radius: 8px;
  overflow: hidden;
  font-size: 14px;
  color: #333;
  background-color: #fff;
}

.el-table th {
  background-color: #f3f4f6 !important;
  font-weight: bold;
  color: #444;
  font-size: 14px;
}

.el-table td {
  background-color: #fff;
  transition: background-color 0.3s;
}

.el-table__row:hover td {
  background-color: #f0f9ff;
}
.detail-card {
  background: #f8fafc;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.detail-card .section {
  flex: 1;
}

.detail-card h4 {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 6px;
  color: #555;
}

.detail-card p, .detail-card li {
  font-size: 14px;
  color: #333;
  margin: 4px 0;
}
/* 标题 */
.page-title {
  font-size: 26px;
  color: #333;
  margin-bottom: 20px;
  font-weight: bold;
}

/* 表格整体 */
table {
  width: 100%;
  border-collapse: collapse;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden; /* 让圆角生效 */
}

/* 表头加一个渐变背景，更有层次 */
thead tr {
  background: #2980b9;
  color: #fff;
}

th {
  padding: 14px 16px;
  text-align: center;
  font-weight: 600;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

td {
  padding: 14px 16px;
  text-align: center;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #444;
}

/* 隔行变色 + hover 行高亮 */
tbody tr:nth-child(odd) {
  background-color: #f9fcfd;
}

tbody tr:hover {
  background-color: #eaf7ff; /* 浅蓝提示 */
}

/* 按钮组 */
.action-btns {
  display: flex;
  flex-wrap: wrap;      /* 关键：可换行 */
  gap: 6px;             /* 行内、换行后的垂直间距都统一 */
  justify-content: center;
}
/* 基础按钮样式 */
.button {
  padding: 8px 14px;
  border: none;
  border-radius: 5px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s, transform 0.1s;
}

/* 按钮悬浮/点击反馈 */
.button:hover {
  filter: brightness(1.05);
}
.button:active {
  transform: scale(0.97);
}

/* 不同颜色按钮 */
.confirm-btn {
  background-color: #f39c12;
  color: #fff;
}
.cancel-btn {
  background-color: #e74c3c;
  color: #fff;
}
.details-btn {
  background-color: #2980b9;
  color: #fff;
}

/* 分页按钮 */
.page-btn {
  background-color: #3498db;
  color: #fff;
  margin: 0 6px;
}
.page-btn:hover {
  filter: brightness(1.1);
}

/* 分页容器 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 20px;
}

.page-btn {
  background-color: #004f85;
  color: white;
}

.page-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
  color: #666;
}
.order-tags {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 13px;
  color: #e67e22;
  justify-content: center;
  align-items: center;
}
.order-details-expanded {
  font-size: 14px;
  color: #444;
  padding: 10px 20px;
  background: #f8f9fa;
  border-radius: 6px;
}

.order-details-expanded ul {
  padding-left: 16px;
  margin: 6px 0;
}

.order-details-expanded li {
  margin-bottom: 4px;
}
.el-tag--warning {
  background: #fff7e6;
  color: #d46b08;
  border: none;
}
.el-tag--success {
  background: #f6ffed;
  color: #389e0d;
  border: none;
}
.el-tag--danger {
  background: #fff1f0;
  color: #cf1322;
  border: none;
}
.el-tag--info {
  background: #f0f5ff;
  color: #2f54eb;
  border: none;
}

/* 按钮 hover 微浮起 */
.el-button {
  transition: transform 0.15s, box-shadow 0.15s;
}
.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

/* 主色（表头 & hover 行）统一 */
.el-table th {
  background: #006dff !important;
  color: #fff;
}
.el-table__row:hover td {
  background-color: #e8f2ff;
}

/* 让展开卡片更像卡片 */
.detail-card {
  background: #fafbfd;
  border: 1px solid #e6f0ff;
  border-radius: 12px;
  padding: 18px 24px;
}
</style>
